<?php

namespace app\api\controller;

use app\common\logic\Data;
use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class Sms extends Base
{
  /**
   * 短信服务器列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function server_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('sms_server_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('sms_server_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      switch ($vo['platform']) {
        case 'aliyun':
          $vo['platform_title'] = '阿里云';
          break;
        case 'tencent':
          $vo['platform_title'] = '腾讯云';
          break;
        case 'huawei':
          $vo['platform_title'] = '华为云';
          break;
        case 'smsbao':
          $vo['platform_title'] = '短信宝';
          break;
        case 'jdcloud':
          $vo['platform_title'] = '京东云';
          break;
        default:
          $vo['platform_title'] = '未知';
          break;
      }
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_server_list()
  {
    $title = input('param.title','','trim');
    if (!empty($title)) {
      $dataList = Db::connect('mongodb')->name('sms_server_list')->field('_id,title')->where('status', 1)->whereLike('title', $title)->order('create_time', 'desc')->select()->toArray();
    }else{
      $dataList = Db::connect('mongodb')->name('sms_server_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    }
    return Result::Success($dataList);
  }
  public function all_tpl_list()
  {
    $title = input('param.title', '', 'trim');
    if (!empty($title)) {
      $dataList = Db::connect('mongodb')->name('sms_tpl_list')->field('_id,title')->where('status', 1)->whereLike('title', $title)->order('create_time', 'desc')->select()->toArray();
    } else {
      $dataList = Db::connect('mongodb')->name('sms_tpl_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    }
    return Result::Success($dataList);
  }
  public function tpl_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'cate_id' => input('param.cate_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id|aliyun_tpl_code|tencent_tpl_code', 'like', $data['title']];
    }
    if (!empty($data['cate_id'])) {
      $where[] = ['cate_id', '=', $data['cate_id']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('sms_tpl_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('sms_tpl_list')->where($where)->count('id');

    $cateList = Db::connect('mongodb')->name('sms_tpl_cate')->field('_id,title')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['cate_title'] = isset($cateListArr[$vo['cate_id']])? $cateListArr[$vo['cate_id']]:'';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function tpl_cate_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('sms_tpl_cate')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('sms_tpl_cate')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_cate_list()
  {
    $selectResult = Db::connect('mongodb')->name('sms_tpl_cate')->field('_id,title,pid,sort')->order('sort', 'desc')->select()->toArray();
    $sdata = new Data();
    foreach ($selectResult as &$vo) {
      $vo['title'] = $vo['title'];
      $vo['ids'] = join(',', $sdata->getArrSubIds($selectResult, $vo['_id'],'_id'));
    }
    $selectResult = $sdata->arr2table($selectResult, '_id');
    return Result::Success($selectResult);
  }
  public function send_log_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
      'send_time_ranges|发送时间'  => 'require',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'ss_id' => input('param.ss_id', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|phone', 'like', $data['title']];
    }
    if (!empty($data['ss_id'])) {
      $where[] = ['ss_id', '=', $data['ss_id']];
    }
    $start_time = strtotime($data['send_time_ranges'][0]);
    $end_time = strtotime($data['send_time_ranges'][1]);
    if ($end_time - $start_time > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('send_sms_log')->field('*')->where($where)->whereBetweenTime('send_time', $start_time, $end_time)->order('send_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('send_sms_log')->where($where)->whereBetweenTime('send_time', $start_time, $end_time)->count('_id');

    $cateList = Db::connect('mongodb')->name('sms_tpl_list')->field('_id,title')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }
    $serverList = Db::connect('mongodb')->name('sms_server_list')->field('_id,title')->select()->toArray();
    $serverListArr = [];
    foreach ($serverList as &$vo) {
      $serverListArr[$vo['_id']] = $vo['title'];
    }

    foreach ($dataList as &$vo) {
      $vo['send_time'] = date('Y-m-d H:i:s', $vo['send_time']);
      $vo['st_title'] = isset($cateListArr[$vo['st_id']]) ? $cateListArr[$vo['st_id']] : '';
      $vo['ss_title'] = isset($serverListArr[$vo['ss_id']]) ? $serverListArr[$vo['ss_id']] : '';
      $vo['read_time'] = (isset($vo['read_time']) && $vo['read_time'] > 0)?date('Y-m-d H:i:s', $vo['read_time']):'';
      $vo['phone'] = substr($vo['phone'], 0, 3).'***'. substr($vo['phone'], -4);
      $platform = '未知';
      switch ($vo['platform']) {
        case 'aliyun':
          $platform = '阿里云';
          break;
        case 'tencent':
          $platform = '腾讯云';
          break;
        case 'huawei':
          $platform = '华为云';
          break;
        case 'jdcloud':
          $platform = '京东云';
          break;
        case 'smsbao':
          $platform = '短信宝';
          break;
      }
      $vo['platform_title'] = $platform;
      $vo['text_num'] = mb_strlen($vo['send_content'])+2+(isset($vo['send_sign'])?mb_strlen($vo['send_sign']):0);
      $vo['send_num'] = ceil($vo['text_num']/67);
      $vo['send_content'] = (isset($vo['send_content_tm'])) ? $vo['send_content_tm'] : $vo['send_content'];
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function del_log_all()
  {
    $rule = [
      'type|清空类型'  => 'require',
    ];
    $data = [
      'ss_id' => input('param.ss_id', '', 'trim'),
      'type' => input('param.type', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $where['uid'] = $this->uid;
    if (!empty($data['ss_id'])) {
      $where['ss_id'] = trim($data['ss_id']);
    }
    if ($data['type'] == 'all') {
      $status = Db::connect('mongodb')->name('send_sms_log')->where($where)->delete();
    } else {
      $start_time = strtotime($data['send_time_ranges'][0]);
      $end_time = strtotime($data['send_time_ranges'][1]);
      if ($end_time - $start_time > 86400 * 90) {
        return Result::Error('时间跨度不能大于90天');
      }
      $status = Db::connect('mongodb')->name('send_sms_log')->where($where)->whereBetweenTime('create_time', $start_time, $end_time)->delete();
    }
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function send_setting()
  {
    if (request()->isPost()) {
      $rule = [
        'ip_limit|来路IP限制'  => 'number',
        'minute_limit|每分钟内发送上限'  => 'number',
        'hour_limit|每小时内发送上限'  => 'number',
        'day_limit|每个自然日内发送上限'  => 'number',
      ];
      $data = [
        'ip_limit' => input('param.ip_limit', '', 'trim'),
        'server_ip' => input('param.server_ip/a', '', 'trim'),
        'minute_limit' => input('param.minute_limit', '', 'trim'),
        'hour_limit' => input('param.hour_limit', '', 'trim'),
        'day_limit' => input('param.day_limit', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['ip_limit'] = intval($data['ip_limit']);
      $data['minute_limit'] = intval($data['minute_limit']);
      $data['hour_limit'] = intval($data['hour_limit']);
      $data['day_limit'] = intval($data['day_limit']);
      $data['server_ip'] = (empty($data['server_ip']))?'':implode(',', $data['server_ip']);
      $hasSetting = Db::connect('mongodb')->name('send_sms_setting')->find();
      if(empty($hasSetting)){
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId();
        Db::connect('mongodb')->name('send_sms_setting')->insert($data);
      }else{
        $this->redis->del('dever:sms:setting:' . $this->uid, 'full');
        Db::connect('mongodb')->name('send_sms_setting')->update($data);
      }
      return Result::Success('','设置成功');
    } else {
      $infoData = Db::connect('mongodb')->name('send_sms_setting')->find();
      if (!empty($infoData) && !empty($infoData['server_ip'])) {
        $infoData['server_ip'] = explode(',', $infoData['server_ip']);
      }
      return json(['code' => 200, 'data' => $infoData, 'msg' => '获取成功']);
    }
  }
  /**
   * 编辑服务器信息
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function edit_server_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'max:128',
        'platform|短信平台'  => 'require',
        'status|配置状态'  => 'require',
        'server_secret|SecretKey'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'platform' => input('param.platform', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'close_msg' => input('param.close_msg', '', 'trim'),
        'aliyun_key_id' => input('param.aliyun_key_id', '', 'trim'),
        'aliyun_key_secret' => input('param.aliyun_key_secret', '', 'trim'),
        'aliyun_region' => input('param.aliyun_region', '', 'trim'),
        'aliyun_sign' => input('param.aliyun_sign', '', 'trim'),
        'tenc_secret_id' => input('param.tenc_secret_id', '', 'trim'),
        'tenc_secret_key' => input('param.tenc_secret_key', '', 'trim'),
        'tenc_sdk_appid' => input('param.tenc_sdk_appid', '', 'trim'),
        'tenc_region' => input('param.tenc_region', '', 'trim'),
        'tenc_sign' => input('param.tenc_sign', '', 'trim'),
        'server_secret' => input('param.server_secret', '', 'trim'),
        'huawei_app_key' => input('param.huawei_app_key', '', 'trim'),
        'huawei_app_secret' => input('param.huawei_app_secret', '', 'trim'),
        'huawei_app_url' => input('param.huawei_app_url', '', 'trim'),
        'huawei_sign_no' => input('param.huawei_sign_no', '', 'trim'),
        'huawei_sign' => input('param.huawei_sign', '', 'trim'),
        'platform_send_type' => input('param.platform_send_type', '', 'trim'),
        'aliyun_called_number' => input('param.aliyun_called_number', '', 'trim'),
        'ak_from' => input('param.ak_from', '', 'trim'),
        'smsbao_password' => input('param.smsbao_password', '', 'trim'),
        'smsbao_username' => input('param.smsbao_username', '', 'trim'),
        'smsbao_sign' => input('param.smsbao_sign', '', 'trim'),
        'jdcloud_access_key_id' => input('param.jdcloud_access_key_id', '', 'trim'),
        'jdcloud_access_key_secret' => input('param.jdcloud_access_key_secret', '', 'trim'),
        'jdcloud_sign' => input('param.jdcloud_sign', '', 'trim'),
        'jdcloud_sign_id' => input('param.jdcloud_sign_id', '', 'trim'),
        'ak_id' => input('param.ak_id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('sms_server_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'sms_mum', '短信配置数量', $limitCount);
      $data['status'] = intval($data['status']);
      $this->redis->del('dever:sms:server:'.$data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('sms_server_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('SS');
        $status = Db::connect('mongodb')->name('sms_server_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('sms_server_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_tpl_cate_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'pid|上级分类'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'pid' => input('param.pid', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('sms_tpl_cate')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('STC');
        $status = Db::connect('mongodb')->name('sms_tpl_cate')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('sms_tpl_cate')->where('_id', $id)->find();
      unset($data['uid']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_tpl_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'cate_id|模板分类'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'jdcloud_tpl' => input('param.jdcloud_tpl', '', 'trim'),
        'jdcloud_tpl_code' => input('param.jdcloud_tpl_code', '', 'trim'),
        'aliyun_tpl' => input('param.aliyun_tpl', '', 'trim'),
        'aliyun_tpl_code' => input('param.aliyun_tpl_code', '', 'trim'),
        'tencent_tpl' => input('param.tencent_tpl', '', 'trim'),
        'tencent_tpl_code' => input('param.tencent_tpl_code', '', 'trim'),
        'huawei_tpl_code' => input('param.huawei_tpl_code', '', 'trim'),
        'huawei_tpl' => input('param.huawei_tpl', '', 'trim'),
        'smsbao_tpl' => input('param.smsbao_tpl', '', 'trim'),
        'cate_id' => input('param.cate_id', '', 'trim'),
        'ak_id' => input('param.ak_id', '', 'trim'),
        'is_selected' => input('param.is_selected', '', 'trim'),
        'platform' => input('param.platform', '', 'trim'),
        'platform_send_type' => input('param.platform_send_type', '', 'trim'),
        'aliyun_voice_code' => input('param.aliyun_voice_code', '', 'trim'),
        'aliyun_voice' => input('param.aliyun_voice', '', 'trim'),
        'aliyun_called_number' => input('param.aliyun_called_number', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      $this->redis->del('dever:sms:template:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('sms_tpl_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('ST');
        $status = Db::connect('mongodb')->name('sms_tpl_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('sms_tpl_list')->where('_id', $id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function del_server()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('sms_server_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_server_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('sms_server_list')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_tpl()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('sms_tpl_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_tpl_cate()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasTpl = Db::connect('mongodb')->name('sms_tpl_list')->where('cate_id', $data['id'])->find();
    if (!empty($hasTpl)) {
      return Result::Error('该分类下存在短信模板，不允许删除');
    }
    $status = Db::connect('mongodb')->name('sms_tpl_cate')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_sms_log()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('send_sms_log')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_sms_log_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('send_sms_log')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function resend_sms_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $list = Db::connect('mongodb')->name('send_sms_log')->whereIn('_id', $data['id'])->select();
    foreach ($list as $key => $vo) {
      $logSms = json_decode($vo['params'],true);
      $logSms['ssl_id'] = $vo['_id'];
      doSendSms($logSms);
    }
    return Result::Success('','任务提交成功，请稍后通过【短信记录】查看发送结果');
  }
  public function send_sms()
  {
    $rule = [
      'ss_id|短信配置'  => 'require',
      'st_id|短信模板'  => 'require',
      'phone|手机号'  => 'require',
    ];
    $data = [
      'ss_id' => input('param.ss_id', '', 'trim'),
      'st_id' => input('param.st_id', '', 'trim'),
      'params_json' => input('param.params', '', 'trim'),
      'phone' => input('param.phone', '', 'trim'),
      'is_filter_bool' => input('param.is_filter_bool', '', 'trim'),
      'filter_id' => input('param.filter_id', '', 'trim'),
      'content' => input('param.content', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    if ($data['is_filter_bool'] == true) {
      $data['is_filter'] = 1;
    }
    $data['phone'] = implode(',',explode("\n",$data['phone']));
    doSendSms($data);
    return Result::Success($data,'任务已提交，请稍后在日志中查看');
  }
  public function all_data()
  {
    $return['date'] = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) - 1);
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'ss_id' => input('param.ss_id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $whereTj['uid'] = $this->uid;
    if (!empty($data['ss_id'])) {
      $whereTj['ss_id'] = $data['ss_id'];
    }
    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    if ($end_date == $start_date) {
      $cycle_type = 'hour';
      $cycle_num = 24;
    } else {
      $cycle_type = 'day';
      $cycle_num = ($end_date - $start_date) / 86400 + 1;
    }
    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $groupField = $cycle_type == 'hour' ? 'only_hour' : 'date';
    $whereTj['send_time'] = ['$gte' => $start_date, '$lte' => $end_date];
    $hasData = mongodb()->selectCollection('send_sms_log_' . $this->uid)->aggregate([
      ['$match' => $whereTj],
      ['$group' => [
        '_id' => '$' . $groupField,
        'sv_sum' => ['$sum' => ['$cond' => [
          'if' => ['$eq' => ['$send_result', true]],
          'then' => 1,
          'else' => 0
        ]]],
        'fv_sum' => ['$sum' => ['$cond' => [
          'if' => ['$eq' => ['$send_result', false]],
          'then' => 1,
          'else' => 0
        ]]]
      ]]
    ]);
    $newData = [];
    foreach ($hasData as $document) {
      $newData[] = (array)$document;
    }
    $fieldCount = [];
    $return['total']['fv'] = 0;
    $return['total']['sv'] = 0;
    foreach ($newData as $key => $vo) {
      $fieldCount[$vo['_id']] = $vo;
      $return['total']['fv'] += $vo['fv_sum'];
      $return['total']['sv'] += $vo['sv_sum'];
    }
    $chartData = [];
    $num_type = !empty($data['_id']) ? '数' : '总数';
    for ($i = 0; $i < $cycle_num; $i++) {
      if ($cycle_type == 'hour') {
        $nowTime = $start_date + $i * 3600;
        $charItem['date'] = date('H', $nowTime) . ':00';
        $charItem['value'] = isset($fieldCount[$charItem['date']]['sv_sum']) ? $fieldCount[$charItem['date']]['sv_sum'] : 0;
        $charItem['category'] = '发送成功' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = isset($fieldCount[$charItem['date']]['fv_sum']) ? $fieldCount[$charItem['date']]['fv_sum'] : 0;
        $charItem['category'] = '发送失败' . $num_type;
        $chartData[] = $charItem;
      } else {
        $nowTime = $start_date + $i * 86400;
        $charItem['date'] = date('Y-m-d', $nowTime);
        $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['sv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['sv_sum'] : 0;
        $charItem['category'] = '发送成功' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['fv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['fv_sum'] : 0;
        $charItem['category'] = '发送失败' . $num_type;
        $chartData[] = $charItem;
      }
    }
    if ($cycle_type == 'day') {
      $charItem['date'] = date('Y-m-d', $end_date);
      $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['sv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['sv_sum'] : 0;
      $charItem['category'] = '发送成功' . $num_type;
      $chartData[] = $charItem;
      $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['fv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['fv_sum'] : 0;
      $charItem['category'] = '发送失败' . $num_type;
      $chartData[] = $charItem;
    }
    $return['total']['total'] = $return['total']['sv']+ $return['total']['fv'];
    $return['total']['fv_sv_rate'] = ($return['total']['total'] > 0) ? round($return['total']['sv'] / $return['total']['total'] * 100, 2) : 0;
    $return['chart'] = $chartData;
    return Result::Success($return);
  }
  public function all_sms_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'ss_id' => input('param.ss_id', '', 'trim'),
      'phone' => input('param.phone', '', 'trim'),
      'group_type' => input('param.group_type', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['ss_id'])) {
      $where['ss_id'] = $data['ss_id'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['ss_id'])) {
      $whereTj[] = ['ss_id', '=', $data['ss_id']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $fromType = '$'.$data['group_type'];
    $hasAds = mongodb()->selectCollection('send_sms_log_' . $this->uid)->aggregate([
      ['$match' => $where],
      ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
      ['$sort' => ['count' => -1]],
      ['$skip' => (int)$skip],
      ['$limit' => (int)$data['pageSize']],
    ]);
    $newData = [];
    foreach ($hasAds as $document) {
      $newData[] = (array)$document;
    }
    $totalNum = Db::connect('mongodb')->name('send_sms_log')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function single_sms_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'ss_id' => input('param.ss_id', '', 'trim'),
      'phone' => input('param.phone', '', 'trim'),
      'group_type' => input('param.group_type', 'phone', 'trim'),
      'sms_tab' => input('param.sms_tab', '1', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 1000, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['ss_id'])) {
      $where['ss_id'] = $data['ss_id'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['phone'])) {
      if ($data['group_type'] == 'phone') {
        $whereTj[] = ['phone', '=', $data['phone']];
      }else{
        $whereTj[] = ['title|_id', '=', $data['phone']];
      }
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    switch ($data['sms_tab']) {
      case '1':
        $fromType = '$ss_id';
        break;
      case '2':
        if ($data['group_type'] == 'phone') {
          $fromType = '$title';
        } else {
          $fromType = '$phone';
        }
        if (!empty($data['ss_id'])) {
          $whereTj[] = ['ss_id', '=', $data['ss_id']];
        }
        break;
      case '3':
        $fromType = '$title';
        if (!empty($data['ss_id'])) {
          $whereTj[] = ['ss_id', '=', $data['ss_id']];
        }
        break;
      default:
        $fromType = '$phone';
        break;
    }
    if ($data['sms_tab'] == '3') {
      $where['send_result'] = true;
      $read_count = mongodb()->selectCollection('send_sms_log_' . $this->uid)->count($where);
      $where['send_result'] = false;
      $unread_count = mongodb()->selectCollection('send_sms_log_' . $this->uid)->count($where);
      $newData = [];
      $itemBuild['_id'] = '已发送成功';
      $itemBuild['count'] = $read_count;
      $newData[] = $itemBuild;
      $itemBuild['_id'] = '发送失败';
      $itemBuild['count'] = $unread_count;
      $newData[] = $itemBuild;
    }else{
      $hasAds = mongodb()->selectCollection('send_sms_log_' . $this->uid)->aggregate([
      ['$match' => $where],
      ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
      ['$sort' => ['count' => -1]],
      ['$skip' => (int)$skip],
      ['$limit' => (int)$data['pageSize']],
    ]);
      $newData = [];
      foreach ($hasAds as $document) {
        $newData[] = (array)$document;
      }
    }
    
    $totalNum = Db::connect('mongodb')->name('send_sms_log')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = ($totalNum == 0)?0:round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
}
